function [tt_vtl dist]= tt_between_vtl(test,from,to,database,threshold)
% computes the travel times between two vtls
% INPUT:
% test: number of the field test
% from: number of first VTL
% to: number of second VTL
% threshold: if travel time is larger than this, the observation will not
% be considered
% OUTPUT:
% tt_vtl: [entry time][travel time(sec)][pace(s/100m)][vel(m/s)] sorted by
% time.

eval(['load lat_lon_' database '.mat']);

% if ~exist('intersection','var')
%     load lat_lon_sparse.mat
% else
%     load lat_lon_smmspb.mat
%     lat=lat{1,intersection};
%     lon=lon{1,intersection};
% end

dist = latlong_to_feet(lat(from,1),lon(from,1),lat(to,1),lon(to,1));
dist = unitsratio('m','ft')*dist;

% if ~exist('threshold','var')
%     load thrs.mat
%     threshold = th(from,to);  %,(dist/5)*3.6); % v=5 in km/h and threshold in s.
% end

allvehs = get_allvehs(test);

[vtl_updates1] = create_vtl_updates(test,lat(from,:),lon(from,:));
[vtl_updates2] = create_vtl_updates(test,lat(to,:),lon(to,:));

vtl_a = vtl_updates1{1,1};
vtl_b = vtl_updates2{1,1};
j = 1;

[r c] = size(vtl_a);

for i=1:r
    if min(vtl_b(:,1)>1000)
        continue
    end
    id = vtl_a(i,1);
    when = vtl_a(i,3);
    s = find(vtl_b(:,1)==id);
    if ~isempty(s)
        tt = (vtl_b(s,3) - when);
        r = find(tt>0,1,'first');
        if ((~isempty(r)) && (tt(r) < threshold))
%             tt_vtl(j,1) = i;
%             tt_vtl(j,2) = s(r);
            tt_vtl(j,1) = vtl_a(i,3);
            tt_vtl(j,2) = tt(r);
            j = j +1;
            vtl_a(i,:) = 1000*ones(size(vtl_a(i,:)));
            vtl_b(s(r),:) = 1000*ones(size(vtl_b(s(r),:)));
        end
    end
end

% time of the observation is defined as the time the trip is finished (exit
% time)
tt_vtl(:,1) = tt_vtl(:,1) + tt_vtl(:,2);

tt_vtl = sortrows(tt_vtl,1);

tt_vtl(:,3) = 100*tt_vtl(:,2) / dist;   % pace in sec/100 meters
tt_vtl(:,4) = 3.6/1.6 * dist ./ tt_vtl(:,2);   % velocity in mph

return;